package com.zjhn.ds.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zjhn.ds.common.BizResult;
import com.zjhn.ds.domain.dto.mt.ControlInfoDto;
import com.zjhn.ds.domain.dto.mt.UserInfoDto;
import com.zjhn.ds.domain.entity.erp.Operator;
import com.zjhn.ds.domain.entity.erp.ProTask;
import com.zjhn.ds.domain.entity.erp.ProTaskDetail;
import com.zjhn.ds.domain.entity.erp.TradeOrderDetail;
import com.zjhn.ds.domain.entity.jlw.GroupSpinner;
import com.zjhn.ds.domain.entity.jlw.GroupStation;
import com.zjhn.ds.domain.entity.jlw.Spinner;
import com.zjhn.ds.domain.entity.jlw.Station;
import com.zjhn.ds.domain.entity.jlw.Workshop;
import com.zjhn.ds.mapper.GroupSpinnerMapper;
import com.zjhn.ds.mapper.GroupStationMapper;
import com.zjhn.ds.mapper.OperatorMapper;
import com.zjhn.ds.mapper.ProTaskDetailMapper;
import com.zjhn.ds.mapper.ProTaskMapper;
import com.zjhn.ds.mapper.SpinnerMapper;
import com.zjhn.ds.mapper.StationMapper;
import com.zjhn.ds.mapper.TradeOrderDetailMapper;
import com.zjhn.ds.mapper.WorkshopMapper;
import com.zjhn.ds.param.ControlInfoParam;
import com.zjhn.ds.service.HomePageService;
import com.zjhn.ds.utils.CommonUtil;
import com.zjhn.ds.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @BelongsProject: ds_jlw
 * @BelongsPackage: com.zjhn.ds.service.impl
 * @Author: sxt
 * @CreateTime: 2023-09-21  10:05
 * @Description:
 * @Version: 1.0
 */
@Slf4j
@Service
public class HomePageServiceImpl implements HomePageService {

    @Resource
    private UserUtil userUtil;

    @Resource
    private CommonUtil commonUtil;

    @Resource
    private SpinnerMapper spinnerMapper;

    @Resource
    private WorkshopMapper workshopMapper;

    @Resource
    private ProTaskMapper proTaskMapper;

    @Resource
    private StationMapper stationMapper;

    @Resource
    private GroupSpinnerMapper groupSpinnerMapper;

    @Resource
    private GroupStationMapper groupStationMapper;

    @Resource
    private OperatorMapper operatorMapper;

    @Resource
    private ProTaskDetailMapper proTaskDetailMapper;

    @Resource
    private TradeOrderDetailMapper tradeOrderDetailMapper;

    /**
     * 登录后获取用户数据
     * @return
     */
    @Override
    public BizResult<UserInfoDto> getUserInfo(Integer app) {
        String abpUserId = userUtil.getUserInfo().getAbpUserId();
        Operator operator = operatorMapper.selectOne(
                new QueryWrapper<Operator>()
                        .eq("id", abpUserId)
                        .eq("IsDeleted", 0)
        );
        if (operator == null)
            return BizResult.fail("用户不存在");


        UserInfoDto res = UserInfoDto.builder()
                .operateId(operator.getId())
                .username(operator.getUsername())
                .userNo(operator.getUserNo())
                .realName(operator.getRealName())
                .departmentId(operator.getDepartmentGuid())
                .department(commonUtil.getDepartment(operator.getDepartmentGuid()))
                .image(operator.getImage())
                .type(0)
                .build();


        if (app != null && app == 1) {
            // app获取登录用户数据
            Spinner spinner = spinnerMapper.selectOne(new QueryWrapper<Spinner>().eq("operate_id", operator.getId()));
            if (spinner != null) {
                res.setType(1);
                res.setWorkshopId(spinner.getWorkshopId());
                res.setWorkshop(commonUtil.getWorkshopById(spinner.getWorkshopId()));
                res.setSpinnerId(spinner.getId());
            }
        } else  {
            // 平板
            List<Workshop> workshops = workshopMapper.selectList(new QueryWrapper<Workshop>().eq("director_id", operator.getId()));
            if (workshops.size() > 1)
                return BizResult.fail("当前用户为多个车间的车间主任,无法获取准确信息");
            if (workshops.size() == 1) {
                // 车间主任
                res.setType(2);
                res.setWorkshopId(workshops.get(0).getId());
                res.setWorkshop(workshops.get(0).getName());
            }
        }
        return BizResult.success(res);
    }

    /**
     * 首页控制台数据
     * @param param
     * @return
     */
    @Override
    public BizResult<ControlInfoDto> controlInfo(ControlInfoParam param) {

        List<ProTask> proTaskList = proTaskMapper
                .selectList(new QueryWrapper<ProTask>()
                        .lambda()
                        .eq(ProTask::getIsDeleted, 0)
                );

        Map<String, List<ProTaskDetail>> proTaskDetailMap = new HashMap<>();
        if (!proTaskList.isEmpty()) {
            List<ProTaskDetail> details = proTaskDetailMapper
                    .selectList(new QueryWrapper<ProTaskDetail>().eq("type", 0));
            if (!details.isEmpty())
                proTaskDetailMap.putAll(details.stream().collect(Collectors.groupingBy(ProTaskDetail::getTaskId)));
        }

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime oneYearAgo = now.minusMonths(1);
        Date monthAgoDate = Date.from(oneYearAgo.atZone(ZoneId.systemDefault()).toInstant());

        List<String> tradeOrderDetailIds = new ArrayList<>();
        Integer notFinish = 0;
        Integer finish = 0;
        for (ProTask proTask : proTaskList) {
            List<ProTaskDetail> details = proTaskDetailMap.get(proTask.getId());
            if (details != null && !details.isEmpty()) {
                if (proTask.getIsFinish() == 1) {
                    if (proTask.getCreationTime().compareTo(monthAgoDate) >= 0)
                        finish++;
                } else {
                    notFinish++;
                }
            }
        }

        ControlInfoDto res = ControlInfoDto.builder()
                .proTaskQty(notFinish)
                .finishQty(finish)
                .spinnerQty(0)
                .stationQty(0)
                .build();
        if (StringUtils.isNotBlank(param.getSpinnerId())) {
            // 挡车工
            GroupSpinner groupSpinner = groupSpinnerMapper.selectOne(new QueryWrapper<GroupSpinner>().eq("spinner_id", param.getSpinnerId()));
            if (groupSpinner != null) {
                List<GroupStation> groupStations = groupStationMapper.selectList(new QueryWrapper<GroupStation>().eq("group_id", groupSpinner.getGroupId()));
                res.setStationQty(groupStations.size());
            }
        }else {
            // 车间主任
            Integer stationQty = stationMapper.selectCount(new QueryWrapper<Station>().eq("workshop_id", param.getWorkshopId()));
            res.setStationQty(stationQty);

            Integer spinnerQty = spinnerMapper.selectCount(new QueryWrapper<Spinner>().eq("workshop_id", param.getWorkshopId()));
            res.setSpinnerQty(spinnerQty);
        }

        // 获取待生成统计表数量
        // 方法2：需要每个 needle 的数量（needle -> cnt）
        List<Map<String, Object>> needleCounts = tradeOrderDetailMapper.selectMaps(
                new QueryWrapper<TradeOrderDetail>()
                        .select("needle", "COUNT(*) AS cnt")
                        .eq("IsDeleted", 0)
                        .groupBy("needle")
        );
        res.setProduceQty(needleCounts.size());

        return BizResult.success(res);
    }
}
